import json
import random
import re
from django.contrib.auth import login
from django.http import JsonResponse, HttpResponse
from django.views import View
from django_redis import get_redis_connection
from apps.users.models import User
from libs.captcha.captcha import captcha
from ronglian_sms_sdk.SmsSDK import SmsSDK
import logging

logger = logging.getLogger('django')


# Create your views here.
class RegisterView(View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')
        uuid = json_dict.get('uuid')
        print([username, password, password2, mobile, allow])
        # sms_code = json_dict.get('sms_code')
        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match('[a-zA-Z0-9_-]{3,20}', username):
            return JsonResponse({'code': 400, 'errmsg': '⽤户名不满⾜规则'})
        if not re.match('^[a-zA-Z0-9-_.]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式不正确'})
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码不⼀致'})
        if not re.match('^1[3578]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '⼿机号码格式不正确'})
        if not allow:
            return JsonResponse({'code': 400, 'errmsg': '必须同意协议'})
        redis_conn = get_redis_connection('default')
        redis_img_code = redis_conn.get('img:%s' % uuid)
        print(redis_img_code, uuid)
        if redis_img_code:
            redis_img_code.decode().lower()
            print(redis_img_code)
            try:
                user = User.objects.create_user(username=username, password=password, mobile=mobile)
                login(request, user)
                return JsonResponse({'code': 200, 'errmsg': '注册成功!'})
            except Exception as e:
                logger.info(e)
                return JsonResponse({'code': 400, 'errmsg': '注册失败!'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '验证码过期'})


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        if count == 0:
            return JsonResponse({'code': 200, 'errmsg': '用户名可以使用√'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '用户名重复'})


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        if count == 0:
            return JsonResponse({'code': 200, 'errmsg': '手机号可以使用√'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '手机号重复'})


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('default')
        redis_conn.setex(name='img:%s' % uuid, time=60, value=text)
        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):
    def get(self, request, mobile, uuid):
        accId = '8a216da87ba59937017c2519099c20f6'
        accToken = '319d40cbd5a242b2bbab2262fdb05337'
        appId = '8a216da87ba59937017c25190afa20fd'
        sms = SmsSDK(accId, accToken, appId)
        sms_code = '%06d' % random.randint(0, 999999)
        try:
            sms.sendMessage('1', mobile, (sms_code, 1))
            redis_conn = get_redis_connection('default')
            redis_conn.setex(name='sms:%s' % mobile, time=60, value=sms_code)
            return JsonResponse({'code': 200, 'msg': '发送成功'})
        except Exception as e:
            logger.info(e)
            return JsonResponse({'code': 400, 'msg': '发送失败'})


class CheckImageCodeView(View):
    def get(self, request, image_code, uuid):
        redis_conn = get_redis_connection('default')
        redis_image_code = redis_conn.get('img:%s' % uuid)
        if redis_image_code:
            if image_code.lower() == redis_image_code.decode().lower():
                return JsonResponse({'code': 200, 'errmsg': '验证成功'})
            else:
                return JsonResponse({'code': 400, 'errmsg': '验证码错误'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '验证码失效，请重新获取'})


class CheckSmsCodeView(View):
    def get(self, request, sms_code, mobile):
        redis_conn = get_redis_connection('default')
        redis_sms_code = redis_conn.get('sms:%s' % mobile)
        if redis_sms_code:
            if sms_code.lower() == redis_sms_code.decode().lower():
                return JsonResponse({'code': 200, 'errmsg': '验证成功'})
            else:
                return JsonResponse({'code': 400, 'errmsg': '验证码错误'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '验证码失效，请重新获取'})
